<template>
  <div class="blog-edit-container">
    <div class="edit-header">
      <h2>{{ isEdit ? '编辑博客' : '写博客' }}</h2>
      <div class="actions">
        <button @click="saveDraft" class="draft-btn">保存草稿</button>
        <button @click="publishBlog" class="publish-btn">{{ isAdmin ? '直接发布' : '提交审核' }}</button>
      </div>
    </div>

    <div class="edit-form">
      <div class="form-group">
        <label>标题：</label>
        <input type="text" v-model="blog.title" placeholder="请输入博客标题" class="title-input">
      </div>

      <div class="form-group">
        <label>标签：</label>
        <div class="tags-input">
          <div class="selected-tags">
            <span v-for="tag in blog.tags" :key="tag" class="tag">
              {{ tag }}
              <i class="fa fa-times" @click="removeTag(tag)"></i>
            </span>
          </div>
          <div class="tag-selector">
            <input 
              type="text" 
              v-model="tagInput"
              @keyup.enter="addTag"
              placeholder="输入标签后按回车，最多5个标签"
              :disabled="blog.tags.length >= 5"
            >
            <div class="suggested-tags" v-if="tagInput && filteredTags.length">
              <div 
                v-for="tag in filteredTags" 
                :key="tag"
                class="suggested-tag"
                @click="selectTag(tag)"
              >
                {{ tag }}
              </div>
            </div>
          </div>
        </div>
        <div class="common-tags">
          <span>常用标签：</span>
          <span 
            v-for="tag in commonTags" 
            :key="tag"
            class="common-tag"
            @click="selectTag(tag)"
            :class="{ disabled: blog.tags.includes(tag) || blog.tags.length >= 5 }"
          >
            {{ tag }}
          </span>
        </div>
      </div>
      
      <div class="form-group">
        <label>内容：</label>
        <textarea 
          v-model="blog.content" 
          class="content-input"
          placeholder="请输入博客内容..."
          rows="20"
        ></textarea>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BlogEditComponent',
  data() {
    return {
      blog: {
        id: null,
        title: '',
        content: '',
        author: '',
        createTime: '',
        updateTime: '',
        status: 'draft',
        views: 0,
        likes: [],
        comments: [],
        tags: []  // 添加标签数组
      },
      isEdit: false,
      currentUser: JSON.parse(localStorage.getItem('currentUser') || '{}'),
      tagInput: '',
      commonTags: ['技术', '生活', '学习', '工作', '心得', '教程', '随笔', '前端', '后端', '设计']
    }
  },
  computed: {
    isAdmin() {
      return this.currentUser.isAdmin
    },
    filteredTags() {
      if (!this.tagInput) return []
      return this.commonTags.filter(tag => 
        tag.toLowerCase().includes(this.tagInput.toLowerCase()) &&
        !this.blog.tags.includes(tag)
      )
    }
  },
  created() {
    if (!this.currentUser.username) {
      alert('请先登录')
      this.$router.push('/login')
      return
    }

    const blogId = this.$route.params.id
    if (blogId) {
      this.loadBlog(parseInt(blogId))
    } else {
      this.blog.author = this.currentUser.username
      this.blog.createTime = new Date().toISOString()
    }
  },
  methods: {
    loadBlog(id) {
      const blogs = JSON.parse(localStorage.getItem('blogs') || '[]')
      const blog = blogs.find(b => b.id === id)
      if (blog) {
        // 检查编辑权限
        if (!this.isAdmin && blog.author !== this.currentUser.username) {
          alert('您没有权限编辑此博客')
          this.$router.push('/blog')
          return
        }
        this.blog = { ...blog }
        this.isEdit = true
      }
    },
    saveDraft() {
      if (!this.validateBlog()) return
      this.saveBlog('draft')
    },
    publishBlog() {
      if (!this.validateBlog()) return
      // 管理员直接发布，普通用户需要审核
      const status = this.isAdmin ? 'published' : 'pending'
      this.saveBlog(status)
    },
    validateBlog() {
      if (!this.blog.title.trim() || !this.blog.content.trim()) {
        alert('标题和内���不能为空')
        return false
      }
      return true
    },
    saveBlog(status) {
      const blogs = JSON.parse(localStorage.getItem('blogs') || '[]')
      const now = new Date().toISOString()
      
      if (this.isEdit) {
        const index = blogs.findIndex(b => b.id === this.blog.id)
        if (index !== -1) {
          this.blog.updateTime = now
          this.blog.status = status
          blogs[index] = { ...this.blog }
        }
      } else {
        this.blog.id = Date.now()
        this.blog.createTime = now
        this.blog.updateTime = now
        this.blog.status = status
        blogs.push(this.blog)
      }

      localStorage.setItem('blogs', JSON.stringify(blogs))
      
      const message = {
        draft: '草稿已保存',
        pending: '博客已提交审核',
        published: '博客已发布'
      }[status]
      
      alert(message)
      this.$router.push('/blog')
    },
    addTag() {
      const tag = this.tagInput.trim()
      if (tag && !this.blog.tags.includes(tag) && this.blog.tags.length < 5) {
        this.blog.tags.push(tag)
        this.tagInput = ''
      }
    },
    removeTag(tag) {
      const index = this.blog.tags.indexOf(tag)
      if (index > -1) {
        this.blog.tags.splice(index, 1)
      }
    },
    selectTag(tag) {
      if (!this.blog.tags.includes(tag) && this.blog.tags.length < 5) {
        this.blog.tags.push(tag)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.blog-edit-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;

  .edit-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      font-size: 24px;
      color: #333;
    }

    .actions {
      display: flex;
      gap: 12px;

      button {
        padding: 8px 20px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.3s ease;

        &.draft-btn {
          background: #f5f5f5;
          color: #666;
          
          &:hover {
            background: #e8e8e8;
          }
        }

        &.publish-btn {
          background: #ee7419;
          color: white;
          
          &:hover {
            background: #d65f0a;
          }
        }
      }
    }
  }

  .edit-form {
    background: white;
    padding: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.08);

    .form-group {
      margin-bottom: 20px;

      label {
        display: block;
        margin-bottom: 8px;
        color: #666;
        font-size: 14px;
      }

      .title-input {
        width: 100%;
        padding: 12px;
        font-size: 18px;
        border: 1px solid #ddd;
        border-radius: 4px;
        
        &:focus {
          outline: none;
          border-color: #ee7419;
        }
      }

      .content-input {
        width: 100%;
        padding: 12px;
        font-size: 16px;
        line-height: 1.6;
        border: 1px solid #ddd;
        border-radius: 4px;
        resize: vertical;
        min-height: 400px;
        
        &:focus {
          outline: none;
          border-color: #ee7419;
        }
      }
    }
  }

  .tags-input {
    margin-top: 8px;

    .selected-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-bottom: 8px;

      .tag {
        display: inline-flex;
        align-items: center;
        padding: 4px 8px;
        background: #e6f7ff;
        color: #1890ff;
        border-radius: 4px;
        font-size: 14px;

        i {
          margin-left: 4px;
          cursor: pointer;
          
          &:hover {
            color: #ff4d4f;
          }
        }
      }
    }

    .tag-selector {
      position: relative;

      input {
        width: 100%;
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;

        &:focus {
          outline: none;
          border-color: #ee7419;
        }

        &:disabled {
          background: #f5f5f5;
          cursor: not-allowed;
        }
      }

      .suggested-tags {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        background: white;
        border: 1px solid #ddd;
        border-radius: 4px;
        margin-top: 4px;
        max-height: 200px;
        overflow-y: auto;
        z-index: 1000;

        .suggested-tag {
          padding: 8px 12px;
          cursor: pointer;

          &:hover {
            background: #f5f5f5;
          }
        }
      }
    }
  }

  .common-tags {
    margin-top: 12px;
    font-size: 14px;
    color: #666;

    .common-tag {
      display: inline-block;
      margin: 0 8px;
      color: #1890ff;
      cursor: pointer;

      &:hover {
        color: #40a9ff;
      }

      &.disabled {
        color: #ccc;
        cursor: not-allowed;
      }
    }
  }
}
</style> 